$(function(){
    var last_scroll_position = 0;

    $(window).on("hashchange load", function(){
        $(window).scrollTop(last_scroll_position);
        switch (getHash()){
            case "menu":
                $(".level_0 li.has_child").removeClass("open");
                break;
            case "search":
                $("#search input").focus();
                break;
        }
    });

    $("a[href^=#]").on("click", function() {
        last_scroll_position = $(window).scrollTop();
    });

    $(window).on("click", function(){
        if(getHash() === "menu") window.location.hash = "";
    });

    $(".menu_button").on("click", function(){
        if(getHash() === "menu") {
            window.location.hash = "";
            return false;
        }
    });

    $(".level_0 > li.has_child > a").on("click", function(){
        $(".level_0 li").removeClass("open");
        $(this).parent().addClass("open");
        return false;
    });

    $(".level_1 > li.has_child > a").on("click", function(){
        $(".level_1 li").removeClass("open");
        $(this).parent().addClass("open");
        return false;
    });

    $(".news_flexslider").flexslider({
        animation: "slide",
        namespace: "news-",
        controlNav: false,
        selector: ".flexslider_slides > li"
    });


    enquire.register("screen and (max-width: 640px)", {
        match: function(){
            $(window).off("resize orientationchange focus", removeGallery);
            if($("#about_gallery").data("flexslider")){
                if($("#about_gallery .about-viewport").length > 0) $("#about_gallery ul").unwrap();
                $("#about_gallery").removeData("flexslider");
            }
            $("#about_gallery").flexslider({
                animation: "slide",
                controlNav: false,
                animationLoop: false,
                namespace: "about-",
                selector: ".gallery_list > li",
                itemWidth: 240,
                minItems: 1,
                maxItems: 2
            });
        },
        unmatch: function(){
            $(window).on("resize orientationchange focus", removeGallery).resize();
        }
    });
});

function removeGallery(){
    $("#about_gallery").flexslider("stop");
    $("#about_gallery ul").removeAttr("style");
    $("#about_gallery ul li").removeAttr("style");
    $("#about_gallery .about-direction-nav").remove();
}

function getHash(){
    var hash = window.location.hash;
    if(hash.indexOf("#") > -1) hash = hash.slice(1);
    return hash;
}